import { onMounted, onUnmounted, watch } from 'vue';

export default {
    mounted(el, binding) {
        // 设置父元素定位，以便loading可以相对定位
        const position = getComputedStyle(el).position;
        if (position ==='static' || position === '') {
            el.style.position ='relative';
        }

        // 确保父元素有明确的高度
        if (el.style.minHeight === '') {
            el.style.minHeight = '100px';
        }

        const Loading = () => import('../components/common/Loading.vue');

        const insertLoading = async () => {
            const { default: LoadingComponent } = await Loading();
            const loading = document.createElement('div');
            el.appendChild(loading);
            const app = createApp(LoadingComponent, { local: true });
            app.mount(loading);
            el.instance = app;

            if (binding.value) {
                el.instance.proxy.visible = true;
            }
        };

        onMounted(insertLoading);

        watch(() => binding.value, (newVal) => {
            if (el.instance) {
                el.instance.proxy.visible = newVal;
            }
        });
    },
    unmounted(el) {
        if (el.instance) {
            el.instance.unmount();
            el.removeChild(el.instance.$el);
            el.instance = null;
        }
    }
};